package com.sky.controller.admin.common;


import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/admin/common")
@Api(tags = "文件上传相关接口")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;


    @PostMapping("/upload")
    @ApiOperation("阿里文件上传")
    public Result upload(MultipartFile file) {
        // 调用util工具类的文件上传放啊
        // 拼接上传名字
        String originalFilename = file.getOriginalFilename();
        String objectName = UUID.randomUUID() + (originalFilename.substring(originalFilename.lastIndexOf(".")));

        // 打印日志
        log.info("上传文件：原始文件名={}，加工后将要放在服务器上的文件名", originalFilename, objectName);
        String url = null;
        try {
            // 文件上传
            url = aliOssUtil.upload(file.getBytes(), objectName);
        } catch (Exception e) {
            log.info("文件上传出错:{}", e.getMessage());
            return Result.error("文件上传出错");
        }
        return Result.success(url);
    }
}
